package it.tukano.odt;

import it.tukano.fun.Tuple2;
import it.tukano.jpgi.test.DecimalSpeller;
import it.tukano.lang.StringExt;
import it.tukano.log.Log;
import it.tukano.swingdeco.containers.JPanelExt;
import it.tukano.swingdeco.text.DecimalDocument;
import it.tukano.swingdeco.text.JTextFieldExt;
import java.awt.GridLayout;
import javax.swing.BorderFactory;

public class OdtCurrencyEditor extends OdtFieldEditor {

    /* default serial version uid*/
    private static final long serialVersionUID = 0;
    private final JTextFieldExt field;
    private final String defaultValue;
    
    public OdtCurrencyEditor() {
        this(1, null, StringExt.EMPTY, true);
    }

    public OdtCurrencyEditor(int size, String label) {
        this(size, label, new StringExt(""), true);
    }

    public OdtCurrencyEditor(int size, String label, StringExt defaultValue, boolean withScript) {
        this.defaultValue = defaultValue.getAsCurrency("");
        this.field = new JTextFieldExt(size).withDocument(new DecimalDocument());
        if(label != null) {
            setBorder(BorderFactory.createTitledBorder(label));
        }
        add(new JPanelExt(new GridLayout(1, 1)).append(field));
        if(withScript) addSideComponent(new ScriptEvaluator(this).getRunButton());
    }

    @Override
    public void setValue(StringExt t) {
        field.setText(t.toString());
    }

    @Override
    public Tuple2<StringExt, String> applyEditorValue(OdtField odtField, String xml) {
        if(odtField == null) {
            Log.message("odt field is null");
        }
        
        StringExt s = new StringExt(new StringExt(field.getText()).getAsCurrency(""));
        String letters = DecimalSpeller.getInstance().spell(s.toString());
        if(odtField != null) {
            String[] spellTargets = odtField.getSpellTargets();
            if(spellTargets != null && spellTargets.length > 0) {
                for (int i = 0; i < spellTargets.length; i++) {
                    String targetToken = spellTargets[i];
                    if(!targetToken.startsWith("{")) targetToken = "{" + targetToken + "}";
                    xml = xml.replace(targetToken, letters);
                }
            }
        }
        return Tuple2.newInstance(s, xml);
    }

    @Override
    public void clearValue() {
        field.setText(defaultValue);
    }

    @Override
    public String getStorableStringValue() {
        return field.getText();
    }
}
